package com.mifengs.commonbase.net;

//import com.facebook.stetho.okhttp3.StethoInterceptor;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.mifengs.commonbase.base.BaseApplication;
import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.FileUtils;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.NetWorkUtils;
import com.mifengs.commonbase.util.PreferenceUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by lihaoqi on 2017/4/11.
 */

public class NetConfig {

    private static File httpCacheDirectory = new File(FileUtils.getCacheDir(), "responses");
    //设置缓存 10M
    private static Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
    //private static OkHttpClient okHttpClient = new OkHttpClient();

    private static Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            String token = PreferenceUtils.getToken();
            Log.d("token-------------",token);
            if (!NetWorkUtils.isNetworkAvailable(BaseApplication.getInstance())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
//                        .header("User-Agent", "mfsc_interface_mfsc_android" + " v_" + DeviceInfoUtil.getAppVersion(BaseApplication.getInstance()))
                        .header("clientType","ANDROID")
                        .header("token",token)
                        .build();
            } else {
                request = request.newBuilder()
//                        .header("User-Agent", "mfsc_interface_mfsc_android" + " v_" + DeviceInfoUtil.getAppVersion(BaseApplication.getInstance()))
                        .header("clientType","ANDROID")
                        .header("token",token)
                        .build();
            }
            Response response = chain.proceed(request);

            if (NetWorkUtils.isNetworkAvailable(BaseApplication.getInstance())) {
                int maxAge = 0 * 60; // 有网络时 设置缓存超时时间0个小时
                response.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }

            return response;
        }
    };


    public static OkHttpClient client = new OkHttpClient.Builder()
            .followRedirects(false)
            .addInterceptor(interceptor)
            // .addInterceptor(new AddToKenInterceptor())
            .connectTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(10, TimeUnit.MINUTES)
            .readTimeout(10, TimeUnit.MINUTES)
            .cache(cache)
//            .dns(OkHttpDns.getInstance())
            .build();





    public static OkHttpClient rlclient = new OkHttpClient.Builder()         // 登录和注册的client 特殊处理
            .followRedirects(false)
            .addInterceptor(interceptor)
            //.addInterceptor(new AddCookiesInterceptor(MallApplication.getInstance(),"ch"))
            .addInterceptor(new ReceivedCookiesInterceptor(BaseApplication.getInstance()))
            .cache(cache).build();


    public static OkHttpClient regclient = new OkHttpClient.Builder()         // 登录和注册的client 特殊处理
            .followRedirects(false)
            .addInterceptor(interceptor)
            .addInterceptor(new AddCookiesInterceptor(BaseApplication.getInstance(), "ch"))
//            .addInterceptor(new ReceivedCookiesInterceptor(BaseApplication.getInstance()))
            .cache(cache).build();


    public static class AddToKenInterceptor implements Interceptor {

        private Context context;
        private String lang;

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain == null)
                LogUtil.i("http", "Addchain == null");
            final Request.Builder builder = chain.request().newBuilder();
            //SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
//            String cookies = PreferenceUtils.getCookies(context);
//            Observable.just(cookies)
//                    .subscribe(new Action1<String>() {
//                        @Override
//                        public void call(String cookie) {
//                            if (cookie.contains("lang=ch")){
//                                cookie = cookie.replace("lang=ch","lang="+lang);
//                            }
//                            if (cookie.contains("lang=en")){
//                                cookie = cookie.replace("lang=en","lang="+lang);
//                            }
//                            //添加cookie
//                            LogUtil.i("http", "AddCookiesInterceptor"+cookie);
//                            builder.addHeader("cookie", cookie);
//                        }
//                    });
            String token = PreferenceUtils.getToken();
            if (!TextUtils.isEmpty(token)) {
                builder.addHeader("cookie", "LS_TOKEN=" + token + ";");
            }
            return chain.proceed(builder.build());
        }
    }


    public static class AddCookiesInterceptor implements Interceptor {
        private Context context;
        private String lang;

        public AddCookiesInterceptor(Context context, String lang) {
            super();
            this.context = context;
            this.lang = lang;

        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain == null)
                LogUtil.i("http", "Addchain == null");
            final Request.Builder builder = chain.request().newBuilder();
            //SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
            String cookies = PreferenceUtils.getCookies(context);
            builder.addHeader("cookie", cookies);
            return chain.proceed(builder.build());
        }
    }


    public static class ReceivedCookiesInterceptor implements Interceptor {
        private Context context;
        SharedPreferences sharedPreferences;

        public ReceivedCookiesInterceptor(Context context) {
            super();
            this.context = context;
            sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (chain == null)
                LogUtil.i("http", "Receivedchain == null");
            final Response originalResponse = chain.proceed(chain.request());
            LogUtil.i("http", "originalResponse" + originalResponse.toString());
            // LogUtil.i("http", "originalResponse" + originalResponse.priorResponse.header("location"));
            if (!originalResponse.headers("set-cookie").isEmpty()) {
                final StringBuffer cookieBuffer = new StringBuffer();
                Observable.from(originalResponse.headers("set-cookie"))
                        .map(new Func1<String, String>() {
                            @Override
                            public String call(String s) {
                                String[] cookieArray = s.split(";");
                                return cookieArray[0];
                            }
                        })
                        .subscribe(new Action1<String>() {
                            @Override
                            public void call(String cookie) {
                                if (cookie.contains("LS_TOKEN=")) {
                                    String[] t = cookie.split("=");
                                    if (t.length == 2) {
                                        String token = t[1];
                                        if (token.length() > 4) {
                                            PreferenceUtils.saveToken(token);
                                        } else {
                                            PreferenceUtils.clearLoginInfo();
                                        }
                                    } else {
                                        List<String> location = originalResponse.headers("location");
                                        if (location.size() > 0) {
                                            Uri mUri = Uri.parse(location.get(0));
                                            String error = mUri.getQueryParameter("error");  //从重定向的 url 中获取error 值
                                            PreferenceUtils.saveError(context, error);
                                        }
                                    }
                                }
                                cookieBuffer.append(cookie).append(";");
                            }
                        });
                String cookies = cookieBuffer.toString();
                LogUtil.i("http", "ReceivedCookiesInterceptor:" + cookies);

            }
            return originalResponse;
        }

    }
}
